package com.qlylkj.lbk.ui.home

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.qlylkj.lbk.base.BaseViewModel
import com.qlylkj.lbk.model.api.ResultResponse
import com.qlylkj.lbk.model.bean.HomeViewType
import com.qlylkj.lbk.model.repository.CommonRepository
import com.qlylkj.lbk.model.repository.CompanyRepository
import com.qlylkj.lbk.model.repository.NewsRepository

class HomeViewModel: BaseViewModel() {

    private val _uiState = MutableLiveData<HomeUiModel>()
    val uiState: LiveData<HomeUiModel>
        get() = _uiState

    private val commonRepository by lazy { CommonRepository() }

    private val newsRepository by lazy { NewsRepository() }

    private val companyRepository by lazy { CompanyRepository() }

    private fun emitUiState(
        homeViewTypeList: MutableList<HomeViewType> = mutableListOf()
    ) {
        val uiModel = HomeUiModel(homeViewTypeList)
        _uiState.value = uiModel
    }

    data class HomeUiModel(
        val homeViewTypeList: MutableList<HomeViewType>
    )

    fun getHomeData(){
        val homeViewTypeList = mutableListOf<HomeViewType>()
        launch {
            val bannerListResult = commonRepository.getBannerList()
            val newsListResult = newsRepository.getNewsList(1,3)
            val coChainListResult = companyRepository.getUserCoChainList("",1,3)
            if (bannerListResult is ResultResponse.SuccessEntity) {
                val bannerList = bannerListResult.data.records
                if(bannerList.isNotEmpty()){
                    homeViewTypeList.add(HomeViewType(HomeViewType.TYPE_BANNER,bannerListResult.data))
                }
            }
            if (newsListResult is ResultResponse.SuccessEntity) {
                val newsList = newsListResult.data.records
                if(newsList.isNotEmpty()){
                    homeViewTypeList.add(HomeViewType(HomeViewType.TYPE_COLUMN_MORE,"链改新闻"))
                    for(it in newsList){
                        homeViewTypeList.add(HomeViewType(HomeViewType.TYPE_NEWS,it))
                    }
                }
            }
            if (coChainListResult is ResultResponse.SuccessEntity) {
                val coChainList = coChainListResult.data.records
                if(coChainList.isNotEmpty()){
                    homeViewTypeList.add(HomeViewType(HomeViewType.TYPE_COLUMN_MORE,"最新上链信息"))
                    for(it in coChainList){
                        homeViewTypeList.add(HomeViewType(HomeViewType.TYPE_CO_CHAIN_INFO,it))
                    }
                }
            }
            emitUiState(homeViewTypeList)
        }
    }

}